package com.tiem_files.filter;

import com.tiem_files.service.UserService;
import com.tiem_files.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@WebFilter("/index.jsp")
public class SignFilter implements Filter {
    private UserService userService=new UserServiceImpl();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp  = (HttpServletResponse) servletResponse;
        Cookie[] cookies =req.getCookies();
       for (Cookie cookie:cookies) {
            if ("uName".equals(cookie.getName())) {
                //查询用户信息
                Map<String,Object> map = userService.findUserBaseInfo(cookie.getValue());
                req.getSession().setAttribute("userBaseInfo",map);
                resp.sendRedirect(req.getContextPath()+"/assets/html/home.jsp");
                return;
            }
        }
    }

    @Override
    public void destroy() {

    }
}
